<?php
/**
 * Created by PhpStorm.
 * User: zhd
 * Date: 2019/3/22
 * Time: 20:36
 */

namespace app\Module\Index\Controller;


use app\Module\Index\Model\ChatModel;
use app\Module\Index\Model\UnreadChatModel;

class ChatController extends CheckAuth
{
    /**
     * 发送信息
     * @verify int    $user_id
     * @verify string $msg 消息
     * @return string
     */
    public function sendAction($user_id, $msg)
    {
        if (mb_strlen($msg, 'UTF-8') > 500) {
            return fail('消息最长字数为500字');
        }
        $chatModel     = new ChatModel();
        $small_user_id = min($user_id, session('userId'));
        $big_user_id   = max($user_id, session('userId'));
        $id            = $chatModel->insert([
            'small_user_id' => $small_user_id,
            'big_user_id'   => $big_user_id,
            'sender_id'     => session('userId'),
            'created'       => now(),
            'msg'           => $msg,
        ]);

        // 新增未读
        $unreadChatModel = new UnreadChatModel();
        $unreadChatModel->addSet([
            'updated'      => now(),
            'last_chat_id' => $id,
        ]);
        $result = $unreadChatModel->update('num=num+1', [
            'user_id'        => session('userId'),
            'target_user_id' => $user_id,
        ]);
        if (empty($result)) {
            $unreadChatModel->insert([
                'user_id'        => session('userId'),
                'target_user_id' => $user_id,
                'updated'        => now(),
                'created'        => now(),
                'last_chat_id'   => $id,
                'num'            => 1,
            ]);
        }

        if (!empty($id)) {
            return success($id);
        } else {
            return fail('发送失败');
        }
    }

    /**
     * 检查未读信息
     *
     * @verify int $user_id
     * @return string
     */
    public function checkUnreadAction($user_id)
    {
        $unreadChatModel = new UnreadChatModel();
        $unreadChatModel->addWhere('num', '0', '>');
        $unreadChatModel->addWhere([
            'user_id'        => $user_id,
            'target_user_id' => session('userId'),
        ]);

        $data = $unreadChatModel->row(null,600);

        if (empty($data)) {
            return success(false);
        } else {
            return success($data['num']);
        }
    }

    /**
     * 更新未读信息
     *
     * @verify int $user_id
     * @return string
     */
    public function updateUnreadAction($user_id)
    {
        // 更新消息为已读
        $unreadChatModel = new UnreadChatModel();
        $unreadChatModel->addWhere('num', '0', '>');
        $unreadChatModel->update(
            [
                'num'     => 0,
                'updated' => now(),
            ],
            [
                'user_id'        => $user_id,
                'target_user_id' => session('userId'),
            ]);

        return success();
    }

    /**
     * 获取聊天列表
     *
     * @verify  int     $user_id
     * @verify  int|null $last_id
     * @verify  int|null $page
     * @verify  int|null $limit
     * @return string
     */
    public function getListAction($user_id, $last_id, $page = 1, $limit = 50)
    {
        if ($page == 1) {
            $unreadChatModel = new UnreadChatModel();
            $unreadChatModel->addWhere('num', '0', '>');
            $unreadChatModel->addWhere([
                'user_id'        => $user_id,
                'target_user_id' => session('userId'),
            ]);

            $data = $unreadChatModel->row();
            if ($data) {
                $this->updateUnreadAction($user_id);
            }
        }

        $small_user_id = min($user_id, session('userId'));
        $big_user_id   = max($user_id, session('userId'));
        $sender_id     = session('userId');
        $chatModel     = new ChatModel();
        $chatModel->setFields([
            'user.id as user_id','user.username', 'user.avatar_url', 'chat.id', 'chat.msg', "(case when chat.sender_id='{$sender_id}' then true else false end) as is_me",
        ]);
        $chatModel->addOrder('chat.created', false);
        if (!empty($last_id)) {
            $chatModel->addWhere('chat.id', $last_id, '>');
        }
        $chatModel->setJoin('user', 'user.id=chat.sender_id');
        $chatModel->setPage($page, $limit);
        $data = $chatModel->select([
            'small_user_id' => $small_user_id,
            'big_user_id'   => $big_user_id,
        ],600);

        return success($data);
    }

    /**
     * 获取未读消息
     *
     * @verify int|null $page
     * @verify int|null $limit
     * @return array|bool
     */
    public function getUnreadAction($page = 1, $limit = 20)
    {
        $unreadChatModel = new UnreadChatModel();
        $unreadChatModel->setFields('user.id as user_id,user.username,user.avatar_url,unread_chat.num,unread_chat.id,chat.msg,chat.created,chat.id as chat_id');
        $unreadChatModel->setJoin('user', 'user.id=unread_chat.user_id');
        $unreadChatModel->setJoin('chat', 'chat.id=unread_chat.last_chat_id');
        $unreadChatModel->addOrder('chat.created', false);
        $unreadChatModel->setPage($page, $limit);
        $unreadChatModel->addWhere([
            'target_user_id' => session('userId'),
        ]);

        $data = $unreadChatModel->select(null,600);
        return success($data);
    }

}